package com.auto.tv.serial.comn;

import android.os.SystemClock;
import android.util.Log;

import com.auto.tv.serial.comn.message.LogManager;
import com.auto.tv.serial.comn.message.RecvMessage;
import com.licheedev.hwutils.ByteUtil;
import com.licheedev.myutils.LogPlus;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 读串口线程
 */
public class SerialReadThread extends Thread {
    private static final String TAG = "SerialReadThread";
    public BufferedInputStream mInputStream;

    public SerialReadThread(InputStream is) {
        Log.d(TAG, "seriel stram: " + is);
        mInputStream = new BufferedInputStream(is);
    }

    @Override
    public void run() {
        byte[] receivedBytes = new byte[1024];
        int receiverSize;
        LogPlus.e("开始读线程");
        while (true) {
            if (isInterrupted()) {
                break;
            }
            try {
                int available = mInputStream.available();
                if (available > 0) {
                    receiverSize = mInputStream.read(receivedBytes);
                    if (receiverSize > 0) {
                        onDataReceive(receivedBytes, receiverSize);
                    }
                } else {
                    // 暂停一点时间，免得一直循环造成CPU占用率过高
                    SystemClock.sleep(1);
                }
            } catch (IOException e) {
                LogPlus.e("读取数据失败", e);
            }
        }
        SerialPortManager.instance().close();
        LogPlus.e("结束读进程");
    }

    /**
     * 处理获取到的数据
     *
     * @param received
     * @param size
     */
    private void onDataReceive(byte[] received, int size) {
        // TODO: 2018/3/22 解决粘包、分包等
        LogManager.instance().clear();
        String hexStr = ByteUtil.bytes2HexStr(received, 0, size);
        LogManager.instance().post(new RecvMessage(hexStr));
    }

    /**
     * 停止读线程
     */
    public void close() {
        try {
            mInputStream.close();
        } catch (IOException e) {
            LogPlus.e("异常", e);
        } finally {
            super.interrupt();
        }
    }
}
